<?php

class ConsultanteController extends CController
{
	const PAGE_SIZE=10;

	/**
	 * @var string specifies the default action to be 'list'.
	 */
	public $defaultAction='list';

	/**
	 * @var CActiveRecord the currently loaded data model instance.
	 */
	private $_consultante;

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'list' and 'show' actions
				'actions'=>array('list','show'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','search','arbol'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Shows a particular consultante.
	 */
	public function actionShow()
	{
		$consultante = $this->loadconsultante();
		$persona = $this->loadpersona($consultante);
		$this->render('show',array('consultante'=>$consultante,'persona'=>$persona));
	}

	/**
	 * Genera el árbol del consultante.
	 */
	public function actionArbol()
	{
		$consultante = $this->loadconsultante();
		$persona = $this->loadpersona($consultante);
		$parientes = $consultante->parientes;
		foreach ($parientes as $pariente) {
			$parientesOrdenados[$pariente->parentesco->tipo] = $pariente;
		}
		$this->render('arbol',array('consultante'=>$consultante,'persona'=>$persona,'parientesOrdenados'=>$parientes));
	}

	/**
	 * Creates a new consultante.
	 * If creation is successful, the browser will be redirected to the 'show' page.
	 */
	public function actionCreate()
	{
		$persona=new persona;
		$consultante=new consultante;
		
		if(isset($_POST['consultante']))
		{
			$consultante->attributes=$_POST['consultante'];
			$persona->attributes=$_POST['persona'];
			if($persona->insert()){
				$consultante->personaId=$persona->id;
				if($consultante->insert()) {
					$this->redirect(array('show','id'=>$consultante->id));
				} else $this->render('show',array('consultante'=>$consultante));
			}
		} else {
			$this->render('create',array('consultante'=>$consultante,'persona'=>$persona));
		} 

	}

	/**
	 * Updates a particular consultante.
	 * If update is successful, the browser will be redirected to the 'show' page.
	 */
	public function actionUpdate()
	{
		$consultante=$this->loadconsultante();
		$persona=$this->loadpersona($consultante);
		if(isset($_POST['consultante']))
		{
			$consultante->attributes=$_POST['consultante'];
			$persona->attributes=$_POST['persona'];
			if($consultante->save() && $persona->save()) 
				$this->redirect(array('show','id'=>$consultante->id));
		}
		$this->render('update',array('consultante'=>$consultante,'persona'=>$persona));
	}

	/**
	 * Deletes a particular consultante.
	 * If deletion is successful, the browser will be redirected to the 'list' page.
	 */
	public function actionDelete()
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadconsultante()->delete();
			$this->redirect(array('list'));
		}
		else
			throw new CHttpException(500,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all consultantes.
	 */
	public function actionList()
	{
		$criteria=new CDbCriteria;

		$pages=new CPagination(consultante::model()->count($criteria));
		$pages->pageSize=self::PAGE_SIZE;
		$pages->applyLimit($criteria);

		$consultanteList=consultante::model()->findAll($criteria);
		
		$i=0;
		foreach ($consultanteList as $consultante) {
			$personaList[$i]=$this->loadpersona($consultante);
			$i++;
		}
		$this->render('list',array(
			'consultanteList'=>$consultanteList,
			'personaList'=>$personaList,
			'pages'=>$pages,
		));
	}


	/**
	 * Buscar consultante.
	 */
	public function actionSearch()
	{
		$persona=new persona;
		if(isset($_POST['persona']))
		{
			$persona->attributes=$_POST['persona'];
		    $criteria=new CDbCriteria;			
		    $where="nombre LIKE '%".($persona->nombre)."%' AND apellido1 LIKE '%".($persona->apellido1)."%' AND apellido2 LIKE '%".($persona->apellido2)."%'";
		    $criteria->condition=$where;
		    $personaList=persona::model()->findAll($criteria);
		    if (sizeof($personaList)>0) {
				$lista_para_criterio="(";
				foreach ( $personaList as $persona ){
					$lista_para_criterio="$lista_para_criterio".$persona->id.",";
				}
				$lista_para_criterio=substr($lista_para_criterio,0,-1).")";
				$criteria->condition="personaId in $lista_para_criterio";
				$pages=new CPagination(consultante::model()->count($criteria));
				$pages->pageSize=self::PAGE_SIZE;
				$pages->applyLimit($criteria);
				$consultanteList=consultante::model()->findAll($criteria);
				$i=0;
				foreach ($consultanteList as $consultante) {
					$personaList[$i]=$this->loadpersona($consultante);
					$i++;
				}				
				$this->render('list',array(
					'consultanteList'=>$consultanteList,
					'personaList'=>$personaList,
					'pages'=>$pages,
				));
			} else {
				$this->render('search',array(
				'persona'=>$persona));
			}
		
		} else $this->render('search',array(
			'persona'=>$persona));
	}

	/**
	 * Manages all consultantes.
	 */
	public function actionAdmin()
	{
		$this->processAdminCommand();

		$criteria=new CDbCriteria;

		$pages=new CPagination(consultante::model()->count($criteria));
		$pages->pageSize=self::PAGE_SIZE;
		$pages->applyLimit($criteria);

		$sort=new CSort('consultante');
		$sort->applyOrder($criteria);

		$consultanteList=consultante::model()->findAll($criteria);

		$this->render('admin',array(
			'consultanteList'=>$consultanteList,
			'pages'=>$pages,
			'sort'=>$sort,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the primary key value. Defaults to null, meaning using the 'id' GET variable
	 */
	public function loadconsultante($id=null)
	{
		if($this->_consultante===null)
		{
			if($id!==null || isset($_GET['id']))
				$this->_consultante=consultante::model()->with('persona','parientes')->findbyPk($id!==null ? $id : $_GET['id']);
			if($this->_consultante===null)
				throw new CHttpException(500,'El consultante no existe.');
		}
		return $this->_consultante;
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the primary key value. Defaults to null, meaning using the 'id' GET variable
	 */
	public function loadpersona($consultante)
	{
		if($consultante!=null)
		{
			$persona=$consultante->persona;
		}
		return $persona;
	}


	/**
	 * Executes any command triggered on the admin page.
	 */
	protected function processAdminCommand()
	{
		if(isset($_POST['command'], $_POST['id']) && $_POST['command']==='delete')
		{
			$this->loadconsultante($_POST['id'])->delete();
			// reload the current page to avoid duplicated delete actions
			$this->refresh();
		}
	}
}
